<!-- 资质类型 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="6" :xs="24" style="border-right: 1px solid #ececec">
        <div class="head-container">
          <el-row>
            <el-col :span="20">
              <h2>资质类型</h2>
            </el-col>
            <el-col :span="2">
              <el-button type="text" size="mini" @click="() => appendFather()"
                ><i
                  style="font-size: 30px; line-height: 50px"
                  class="el-icon-circle-plus-outline el-icon--right"
                ></i>
              </el-button>
            </el-col>
          </el-row>
          <div class="iptSea">
            <el-input
              v-model="filterText"
              placeholder="请输入类型"
              clearable
              size="mini"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
        </div>
        <div class="head-container" style="height: 700px; overflow-y: auto">
          <el-tree
            :data="treeData"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            draggable
            @node-drop="handleDrop"
            :allow-drop="allowDrop"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span style="color: #2b2b2b">
                <!--          <i class="vxe-icon&#45;&#45;menu"></i>-->
                {{ node.label }}</span
              >
              <span class="activeNode">
                <el-button
                  type="text"
                  size="mini"
                  @click="() => append(node, data)"
                >
                  <i class="el-icon-circle-plus-outline el-icon--right"></i>
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => edit(node, data)"
                  ><i class="el-icon-edit-outline el-icon--right"></i>
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => remove(node, data)"
                  ><i class="el-icon-circle-close el-icon--right"></i>
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="18" :xs="24" style="margin-top: 20px">
        <div class="mb8">
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-input
              v-model="queryParams.level"
              placeholder="请输入资质级别"
              clearable
              size="small"
              style="width: 300px"
            >
              <el-button
                slot="append"
                @click="handleQuery"
                style="
                  height: 40px;
                  background: #1267fa;
                  color: #fff;
                  font-size: 14px;
                "
                >搜索</el-button
              >
            </el-input>
          </el-form>
          <el-button
            size="default"
            @click="handleAdd"
            v-hasPermi="['qualification:qualificationType:add']"
            style="
              margin-right: 10px;
              background-color: #1267fa;
              color: #fff;
              border: none;
            "
          >
            <span>+</span> 新建资质
          </el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="qualificationTypeList"
          :height="tableHight"
          @selection-change="handleSelectionChange"
        >
          <template slot="empty" class="emptyBg">
            <img src="@/assets/images/empty.jpg" alt="" />
          </template>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="资质名称" align="center" prop="name" />
          <el-table-column label="级别" align="center" prop="level" />
          <el-table-column label="预警天数" align="center" prop="earlyWarning">
            <template slot-scope="scope">
              {{ scope.row.earlyWarning }}天
            </template>
          </el-table-column>
          <el-table-column label="资质标准" align="center" prop="remark" />
          <el-table-column label="创建人" align="center" prop="createBy" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                style="color: #1267fa"
                @click="handleUpdate(scope.row, 'view')"
                v-hasPermi="['qualification:qualificationType:query']"
                >查看</el-button
              >
              <el-button
                size="mini"
                type="text"
                style="color: #1267fa"
                @click="handleUpdate(scope.row, 'edit')"
                v-hasPermi="['qualification:qualificationType:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                style="color: #1267fa"
                @click="handleDelete(scope.row)"
                v-hasPermi="['qualification:qualificationType:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          prev-text="上一页"
          next-text="下一页"
          background
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          layout=" ->,total, sizes, prev, pager, next, jumper "
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <el-dialog
      :title="treeTitle"
      v-if="treeOpen"
      :visible.sync="treeOpen"
      width="300px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="treeOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改资质类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="53%" append-to-body>
      <el-form
        ref="form1"
        :model="form"
        :rules="rules"
        label-width="80px"
        :disabled="'view' == formType"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="parentId">
              <treeselect
                :disabled="'view' == formType"
                :disable-branch-nodes="true"
                v-model="form.parentId"
                :options="treeData"
                :show-count="true"
                placeholder="请选择类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入资质名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="级别" prop="level">
              <el-input v-model="form.level" placeholder="请输入级别" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预警天数" prop="earlyWarning">
              <!--              <el-input v-model="form.earlyWarning" placeholder="请输入预警天数" />-->
              <el-input-number
                style="width: 65px"
                v-model="form.earlyWarning"
                placeholder="请输入预警天数"
                :controls="false"
                :min="1"
                :max="999"
              ></el-input-number>
              天
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="资质标准" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入资质标准"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="'edit' == formType">
        <el-button type="primary" @click="submitForm('form1')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQualificationType,
  getQualificationType,
  delQualificationType,
  addQualificationType,
  updateQualificationType,
  exportQualificationType,
  qualTreeselect,
  sortQualificationType,
} from "@/api/qualification/qualificationType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "QualificationType",
  components: { Treeselect },
  data() {
    return {
      tableHight: window.innerHeight - 330,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资质类型表格数据
      qualificationTypeList: [],
      // 弹出层标题
      title: "",
      treeTitle: "",
      // 是否显示弹出层
      open: false,
      treeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        name: null,
        type: "1",
        level: null,
        earlyWarning: null,
      },
      // 表单参数
      form: {},
      formType: "edit",
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "资质类型不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "资质名称不能为空", trigger: "blur" },
        ],
        level: [{ required: true, message: "级别不能为空", trigger: "blur" }],
        earlyWarning: [
          { required: true, message: "预警天数不能为空", trigger: "blur" },
        ],
      },
      filterText: "",
      treeData: [],
      treeProps: {
        children: "children",
        label: "label",
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.tableHight = window.innerHeight - 330;
      })();
    };
  },
  activated() {
    this.tableHight = window.innerHeight - 330;
  },
  methods: {
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    getTreeselect() {
      qualTreeselect({
        type: "0",
      }).then((response) => {
        this.treeData = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.queryParams.ancestors = data.id;
      this.getList();
    },
    appendFather() {
      this.form = {};
      this.form["parentId"] = 0;
      this.form["type"] = 0;
      this.form["sort"] = this.treeData.length + 1;
      this.treeTitle = "新建资质类型";
      this.treeOpen = true;
    },
    append(node, data) {
      this.form = {};
      this.form["parentId"] = data.id;
      this.form["type"] = 0;
      this.form["sort"] = node.childNodes.length + 1;
      this.treeTitle = "新建子类型";
      this.treeOpen = true;
    },
    edit(node, data) {
      getQualificationType(data.id).then((response) => {
        this.form = response.data;
        this.treeTitle = "编辑类型名称";
        this.treeOpen = true;
      });
    },
    remove(node, data) {
      if (node.childNodes.length > 0) {
        this.msgError("请先删除子节点");
        return false;
      }
      this.form = {};
      this.form["type"] = data.type;
      this.form["id"] = data.id;
      this.form["name"] = data.label;
      this.handleDelete(this.form);
    },
    //禁用跨级排序（同一类型只能有一个资质名称，限制较大，禁用）
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.level === dropNode.level) {
        if (draggingNode.parent.id === dropNode.parent.id) {
          // 向上拖拽 || 向下拖拽
          return type === "prev" || type === "next";
        }
      } else {
        // 不同级进行处理
        return false;
      }
    },
    //拖拽排序
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let paramData = [];
      // 当拖拽类型不为inner,说明只是同级或者跨级排序，只需要寻找目标节点的父ID，获取其对象以及所有的子节点，并为子节点设置当前对象的ID为父ID即可
      // 当拖拽类型为inner，说明拖拽节点成为了目标节点的子节点，只需要获取目标节点对象即可
      var data = dropType != "inner" ? dropNode.parent.data : dropNode.data;
      var nodeData =
        dropNode.level == 1 && dropType != "inner" ? data : data.children;
      // 设置父ID,当level为1说明在第一级，pid为空
      nodeData.forEach((element) => {
        element.pid = data.id;
      });
      nodeData.forEach((element, i) => {
        paramData.push({
          id: element.id,
          parentId: element.pid ? element.pid : 0,
          sort: i + 1,
        });
      });
      console.log(paramData);
      sortQualificationType(paramData).then((response) => {
        this.msgSuccess("排序成功！");
      });
    },
    /** 查询资质类型列表 */
    getList() {
      this.loading = true;
      this.queryParams.type = "1";
      listQualificationType(this.queryParams).then((response) => {
        this.qualificationTypeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        name: null,
        type: null,
        level: null,
        earlyWarning: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.formType = "edit";
      this.reset();

      this.form["type"] = 1;
      this.open = true;
      this.title = "添加资质类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row, formType) {
      this.reset();
      const id = row.id || this.ids;
      this.formType = formType;
      getQualificationType(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资质类型";
      });
    },
    /** 提交按钮 */
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateQualificationType(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.treeOpen = false;
                this.getList();
                this.getTreeselect();
              }
            });
          } else {
            addQualificationType(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.queryParams = {
                  ancestors: this.form.parentId,
                };
                this.getList();
                this.getTreeselect();
              }
              // else {
              //   this.msgError(response.msg);
              // }
              this.open = false;
              this.treeOpen = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delQualificationType(ids);
        })
        .then((response) => {
          if (response.code === 200) {
            this.getList();
            this.getTreeselect();
            this.msgSuccess("删除成功");
          } else {
            this.msgError(response.msg);
          }
        })
        .catch(function () {});
    },
  },
};
</script>
<style lang="less" scoped>
.el-form {
  .el-input {
    /deep/.el-input__inner {
      height: 40px;
    }
  }
}
.iptSea {
  /deep/.el-input__inner {
    height: 40px;
  }
}
/deep/input::-webkit-input-placeholder {
  font-size: 14px;
}
.mb8 {
  display: flex;
  justify-content: space-between;
}
.activeNode {
  display: none;
}

.el-tree-node__content:hover .activeNode {
  display: inline-block;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-pagination {
  margin-top: 24px;
  /deep/ .el-pagination__total {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    margin-right: 25px;
  }
  /deep/ .btn-prev {
    width: 80px;
    height: 40px;
    text-align: center;
  }
  /deep/ .btn-next {
    width: 80px;
    height: 40px;
    text-align: center;
  }
  /deep/ .number {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .el-input__inner {
    // width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .more {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .el-pagination__jump {
    .el-input__inner {
      width: 40px;
      height: 40px;
    }
  }
}
</style>
